<?php
	class DB {
	    private $db;
	
	    function __construct($db_config) {
	        // 连接数据库
	        $dsn = "pgsql:host={$db_config['host']};port={$db_config['port']};dbname={$db_config['dbname']}";
	        $options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
	        $this->db = new PDO($dsn, $db_config['user'], $db_config['password'], $options);
	    }
		
		/*-------------------------------------------------------------------------------------------------------*/
		//查询数量
	    function select_count($table_name, $condition='') {
	        // 参数验证
	        if (!is_string($table_name) || !is_string($condition)) {
	            throw new InvalidArgumentException('参数必须为字符串');
	        }
	
	        // 缓存查询结果
	        $cache_key = 'select_count_' . $table_name . '_' . $condition;
	        $result = apc_fetch($cache_key);
	        if ($result !== false) {
	            return $result;
	        }
	
	        // 防止SQL注入攻击
	        $stmt = $this->db->prepare("SELECT count(*) FROM $table_name WHERE $condition");
	
	        // 查询数据库
	        $stmt->execute();
	        $row = $stmt->fetch(PDO::FETCH_NUM);
	        $result = $row[0];
	
	        // 将结果缓存起来
	        apc_store($cache_key, $result, 60);
	
	        return $result;
	    }
		
		/*-------------------------------------------------------------------------------------------------------*/
		//查询返回结果
		function select_data($col, $table_name, $condition = '', $db) {
		    // 参数验证
		    if (!is_string($col) || !is_string($table_name) || !is_string($condition)) {
		        throw new InvalidArgumentException('参数必须为字符串');
		    }
		
		    // 防止SQL注入攻击
		    $sql = "SELECT $col FROM $table_name";
		    if (!empty($condition)) {
		        $sql .= " WHERE $condition";
		    }
		    $stmt = $db->prepare($sql);
		
		    // 查询数据库
		    $stmt->execute();
		    $arr = $stmt->fetchAll(PDO::FETCH_NUM);
		
		    return $arr;
		}
		
		/*-------------------------------------------------------------------------------------------------------*/
		//查询返回结果带页面
		function select_data_page($table_name, $col, $page = 1, $num = 10, $condition = '', $db) {
		    // 参数验证
		    if (!is_string($table_name) || !is_string($col) || !is_string($condition) || !is_int($page) || !is_int($num)) {
		        throw new InvalidArgumentException('参数类型错误');
		    }
		
		    // 防止SQL注入攻击
		    $sql = "SELECT $col FROM $table_name";
		    if (!empty($condition)) {
		        $sql .= " WHERE $condition";
		    }
		    $sql .= " LIMIT $num OFFSET " . ($page - 1) * $num;
		
		    // 查询数据库
		    $stmt = $db->prepare($sql);
		    $stmt->execute();
		    $arr = $stmt->fetchAll(PDO::FETCH_NUM);
		
		    return json_encode($arr);
		}
		
		/*-------------------------------------------------------------------------------------------------------*/
		//插入数据
		function insert_data($table_name, $columns, $values, $db) {
		    // 参数验证
		    if (!is_string($table_name) || !is_array($columns) || !is_array($values)) {
		        throw new InvalidArgumentException('参数类型错误');
		    }
		
		    // 构建SQL语句
		    $columns_str = implode(',', $columns);
		    $placeholders = implode(',', array_fill(0, count($values), '?'));
		    $sql = "INSERT INTO $table_name ($columns_str) VALUES ($placeholders)";
		
		    // 执行SQL语句
		    try {
		        $stmt = $db->prepare($sql);
		        $stmt->execute($values);
		        return "success";
		    } catch (PDOException $e) {
		        return "error";
		    }
		}
		/*-------------------------------------------------------------------------------------------------------*/
		//更新数据库数据
		function update_data($table_name, $set_values, $condition) {
		    include 'sys.php';
		    $sql = "UPDATE " . $table_name . " SET " . $set_values . " WHERE " . $condition;
		    $ret = pg_query($db, $sql);
		    //成功返回success，失败返回error，注释掉的语句可以看具体失败返回语句
		    if (!$ret) {
		        return "error";
		        //echo pg_last_error($db);
		    } else {
		        return "success";
		    }
		}
		/*-------------------------------------------------------------------------------------------------------*/
		//删除数据库数据
		function delete_data($table_name, $condition, $db) {
		    //预处理 SQL 语句，避免 SQL 注入攻击
		    $stmt = $db->prepare("DELETE FROM $table_name WHERE $condition");
		    
		    //执行 SQL 语句
		    if ($stmt->execute()) {
		        return "success";
		    } else {
		        return "error";
		    }
		}


	}
	//从数据库返回数量函数
	function select_count($table_name,$condition){
		//返回值默认为error，如果有返回值则返回数量，没有则返回error
		include 'sys.php';	
		$result='error';
		$sql ="SELECT count(*) from ".$table_name." where ".$condition;
		$ret = pg_query($db, $sql);
		while($row = pg_fetch_row($ret)){
			$result=$row[0];
		}
		return $result;
	}
	//从数据库返回查询函数
	function select_data($col,$table_name,$condition){
		//返回值默认为error，如果有返回值则返回数量，没有则返回error
		include 'sys.php';
		$result='error';
		$arr=array();
		$num=0;
		$sql ="SELECT ".$col." from ".$table_name." where ".$condition;
		//echo $sql;
		$ret = pg_query($db, $sql);
		while($row = pg_fetch_row($ret)){
			$arr[$num]=$row;
			$num+=1;
		}
		return json_encode($arr);	
	}
	//从数据库返回查询函数_带页数
	function select_data_page($col,$table_name,$condition,$page,$num){
		//返回值默认为error，如果有返回值则返回数量，没有则返回error
		$page_s=strval(($page-1)*$num);
		include 'sys.php';
		$result='error';
		$arr=array();
		$num=0;
		$sql ="SELECT ".$col." from ".$table_name." where ".$condition."limit ".$num." offset ".$page;
		$ret = pg_query($db, $sql);
		while($row = pg_fetch_row($ret)){
			$arr[$num]=$row;
			$num+=1;
		}
		return json_encode($arr);	
	}
	//向数据库表插入数据
	function insert_full_data($table_name,$value){
		include 'sys.php';
		$sql="insert into ".$table_name." values (".$value.");";
		$ret = pg_query($db, $sql);
		//成功返回success，失败返回error，注释掉的语句可以看具体失败返回语句
		if(!$ret){
			return "error";
			//echo pg_last_error($db);
		}else{
			return "success";
		} 
	}
	//删除数据库数据
	function delete_data($table_name,$condition){
		//返回值默认为error，如果有返回值则返回数量，没有则返回error
		include 'sys.php';
		$sql ="delete from ".$table_name." where ".$condition;
		$ret = pg_query($db, $sql);
		//成功返回success，失败返回error，注释掉的语句可以看具体失败返回语句
		if(!$ret){
			return "error";
			//echo pg_last_error($db);
		}else{
			return "success";
		} 
	}
	//更新数据库数据
	function update_data($table_name,$col,$condition){
		//返回值默认为error，如果有返回值则返回数量，没有则返回error
		include 'sys.php';
		$sql ="update ".$table_name." set ".$col." where ".$condition;
		$ret = pg_query($db, $sql);
		//成功返回success，失败返回error，注释掉的语句可以看具体失败返回语句
		if(!$ret){
			return "error";
			//echo pg_last_error($db);
		}else{
			return "success";
		} 
	}
?>